package request

import (
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"zsc-boot/app/customer/model"
	layerModel "zsc-boot/app/system_layer/model"
	layerSvc "zsc-boot/app/system_layer/service"
	"zsc-boot/core/orm"
)

type OrderReq struct {
	Type      string `form:"type" json:"type"` //add为加帐单order为帐单
	StartDate string `form:"startDate" json:"startDate"`
	EndDate   string `form:"endDate" json:"endDate"`
	ChannelId uint   `form:"channelId" json:"channelId"`
}

func (o OrderReq) GetModel() schema.Tabler {
	if o.Type == "orderAdd" {
		return &model.OrderAdd{}
	} else if o.Type == "order" {
		return &model.Order{}
	}
	return nil
}

type ChannelReportReq struct {
	DateStart string `form:"startDate" json:"dateStart"`
	DateEnd   string `form:"endDate" json:"dateEnd"`
	DepId     uint   `form:"depId" json:"depId"`
}

func (req ChannelReportReq) BuildWhere(db *gorm.DB) *gorm.DB {
	if req.DepId != 0 {
		var depInfo layerModel.ServiceDepartment
		orm.GetDb().Preload("MembersList").Preload("Children.MembersList").
			Preload("Children.Children.MembersList").Preload("Children.Children.Children.MembersList").
			Where("id = ?", req.DepId).Find(&depInfo)
		userList := layerSvc.ServiceDepartmentService.GetDepUsers([]layerModel.ServiceDepartment{depInfo})

		userIds := make([]uint, 0, len(userList))
		for _, user := range userList {
			userIds = append(userIds, user.ID)
		}
		db = db.Where("user_id IN (?)", userIds)
	}
	if req.DateStart != "" {
		db = db.Where("created_at >= ?", req.DateStart+" 00:00:00")
	}
	if req.DateEnd != "" {
		db = db.Where("created_at <= ?", req.DateEnd+" 23:59:59")
	}

	return db
}

func (req ChannelReportReq) BuildOrderWhere(db *gorm.DB) *gorm.DB {
	if req.DepId != 0 {
		db = db.Where("dep_id = ?", req.DepId)
	}
	if req.DateStart != "" {
		db = db.Where("created_at >= ?", req.DateStart+" 00:00:00")
	}
	if req.DateEnd != "" {
		db = db.Where("created_at <= ?", req.DateEnd+" 23:59:59")
	}

	return db
}
